<template>
  <el-cascader
    :value="defaultCascaderValue"
    :options="treeData"
    :props="props"
    separator="/"
    @change="changeValue"
    clearable
    placeholder="部门"
  />
</template>

<script>
import { getDepartments } from '../../../apis/department.js'
import { transListToTreeData } from '../../../utils'
export default {
  props: {
    value: {
      type: Number, // 存储的是部门的id  3 4 5
      default: null
    },
    reset: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      treeData: [],
      data2: [],
      defaultCascaderValue: [],
      props: {
        label: 'name', // 要展示的字段
        value: 'id' // 要存储的字段
      }
    }
  },
  watch: {
    value(newValue) {
      if (newValue === null) return
      this.data2 = [newValue]
      this.traverseData(this.treeData)
    }
  },
  methods: {
    async getDepartments() {
      const { data } = await getDepartments()
      this.treeData = transListToTreeData(data.data, 0)
    },

    //递归完成回显
    traverseData(data, parentIds = []) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const ids = [...parentIds, item.id]
        if (this.data2.includes(item.id)) {
          this.defaultCascaderValue = [...ids] //回显赋值
        }

        if (item.children && item.children.length > 0) {
          this.traverseData(item.children, ids)
        }
      }
    },
    changeValue(list) {
      if (list.length > 0) {
        this.$emit('input', list[list.length - 1]) // 将最后一个id取出来传出去
      } else {
        this.$emit('input', null)
      }
    },
    __reset() {
      // 重置 defaultCascaderValue 为初始值，并确保视图更新
      this.defaultCascaderValue = []
      this.$emit('input', null) // 向父组件传递重置事件
    }
  },
  created() {
    this.getDepartments()
    if (this.reset) {
      this.reset()
    }
    this.__reset()
  }
}
</script>

<style></style>
